package com.lch.mebatis.v1;

import com.lch.mebatis.v1.bean.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author: liuchenhui
 * @create: 2019-05-09 22:14
 **/
public class LchExecutor {

    public <T> T query(String sql, Object paramer) {
        Connection conn = null;
        Statement stmt = null;
        LchBlog lchBlog = new LchBlog();

        try {
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 打开连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gp-mybatis", "root", "fdjr34");

            // 执行查询
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(String.format(sql, paramer));

            // 获取结果集
            while (rs.next()) {
                Integer bid = rs.getInt("bid");
                String name = rs.getString("name");
                Integer authorId = rs.getInt("author_id");
                lchBlog.setAuthorId(authorId);
                lchBlog.setBid(bid);
                lchBlog.setName(name);
            }
            System.out.println(lchBlog);

            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        return (T) lchBlog;
    }
}
